import json
import socket
import threading


def server():  # 服务端
    # socket.AF_INET:基于IPV4;socket.SOCK_STREAM:基于TCP/IP
    server_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_.bind(('localhost', 8000))  # 监听8000端口
    server_.listen(5)  # 最多允许5个链接

    while True:
        # 等待浏览器访问
        conn, addr = server_.accept()
        # 接收浏览器发送来的请求内容
        data = json.loads(conn.recv(1024).decode('utf-8'))  # 接收1024个字符
        print(f"服务端：来自客户端{data['name']}的：{data['message']}")

        # 给浏览器返回内容，b'字符串'：将字符串格式化为bytes类型
        conn.send(b"HTTP/1.1 200 OK\r\nContent-Type:text/html; charset=utf-8\r\n\r\n")
        conn.send(f"收到{data['name']}的{data['message']}".encode("utf-8"))


if __name__ == '__main__':
    s = threading.Thread(target=server)
    s.start()
